package ch.drshit.model.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileSystemModel {

	public FileSystemModel() {

	}

	/**
	 * Opens a FileChooser in the User Pictures Directroy (only Windows 7 else
	 * in current Directory) Accepts only Images and returns a BufferedImage or
	 * null
	 * 
	 * @return
	 */
	public BufferedImage getBufferedImageFromSystem() {
		JFileChooser jfc = this.getJFileChooser();
		FileFilter imageFilter = new FileNameExtensionFilter("Bilder",
				ImageIO.getReaderFileSuffixes());
		jfc.setFileFilter(imageFilter);
		jfc.setAcceptAllFileFilterUsed(false);
		int jfcResult = jfc.showOpenDialog(null);
		if (jfcResult == JFileChooser.APPROVE_OPTION) {
			File imageFile = jfc.getSelectedFile();
			BufferedImage bi;
			try {
				bi = ImageIO.read(imageFile);
				return bi;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}

		}
		return null;
	}

	public boolean saveBufferedImageToSystem(BufferedImage bi) {
		JFileChooser jfc = this.getJFileChooser();
		File outputfile = new File("drshit_image.png");
		jfc.setSelectedFile(outputfile);
		int jfcResult = jfc.showSaveDialog(null);
		if (jfcResult == JFileChooser.APPROVE_OPTION) {
			outputfile = jfc.getSelectedFile();
			String filename = outputfile.toString();
			if (!filename.endsWith(".png")) {
				filename += ".png";
				outputfile = new File(filename);
			}
			try {
				ImageIO.write(bi, "png", outputfile);
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

	private JFileChooser getJFileChooser() {
		String osname = System.getProperty("os.name").toLowerCase();
		JFileChooser jfc;
		if (osname.equals("windows 7")) {
			String username = System.getProperty("user.name");
			File f = new File("C:\\Users\\" + username + "\\Pictures");
			jfc = new JFileChooser(f);
		} else {
			jfc = new JFileChooser();
		}
		return jfc;
	}

}
